package com.jd.onlinequery.common.utils;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


/**
 * HTTP工具类
 * @author sylis
 *
 */
public abstract class HttpUtil {
    
    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
    
    private static final String UTF8 = "UTF-8";
    
    /**
     * 请求OSB接口
     * @param url
     * @param paramMap
     * @return
     * @throws Exception
     */
    public static String invokeOsbInteface(String url, Map<String, Object> paramMap) throws Exception {
        CloseableHttpClient httpClient = null;
        HttpPost post = null;
        CloseableHttpResponse httpResponse = null;
        try {
            httpClient = getHttpClient();
            post = new HttpPost(url);
            post.addHeader("appid", paramMap.get("appid").toString());
            post.addHeader("appkey", paramMap.get("appkey").toString());
            paramMap.remove("appid");
            paramMap.remove("appkey");
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            Iterator<String> iter = paramMap.keySet().iterator();
            while (iter.hasNext()) {
                String key = iter.next();
                params.add(new BasicNameValuePair(key, (String) paramMap.get(key)));
            }
            UrlEncodedFormEntity entity2 = new UrlEncodedFormEntity(params, UTF8);
            post.setEntity(entity2);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(Constants.OSB_TIME_OUT)
                    .setConnectTimeout(Constants.OSB_TIME_OUT).build();
            post.setConfig(requestConfig);

            httpResponse = httpClient.execute(post);

            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(httpResponse.getEntity(), UTF8);
                return result;
            }
        } catch (Exception e) {
            logger.error(":失败" + e.getMessage(), e);
            throw e;
        } finally {
            if (null != httpResponse) {
                try {
                    // 释放链接
                    httpResponse.close();
                    logger.info("close http response");
                } catch (Exception e) {
                    logger.error("close http response fail", e);
                    throw e;
                }
            }
            if (null != post) {
                try {
                    // 释放链接
                    post.abort();
                } catch (Exception e) {
                    logger.error("close request fail", e);
                    throw e;
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    logger.error("close httpClient fail", e);
                }
            }
        }
        return null;
    }
    
    public static CloseableHttpClient getHttpClient(){
        CloseableHttpClient clbhttpClient = HttpClients.createDefault();
        return clbhttpClient;
    }
}
